import Axios from 'axios'
import Qs from 'qs'

export default function ajax(url='',params = {},type = 'GET',contentType = 'form'){
    let promise;
    return new Promise((resovle,reject) => {
        if('GET' === type.toUpperCase()){
            // 2.1 拼接请求字符串
            let paramsStr = '';
            Object.keys(params).forEach(key =>{
                paramsStr += key + '=' + params[key] + '&'
            });
            // 2.2 过滤最后的&
            if(paramsStr !== ''){
                paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'))
            }
            // 2.3 完整路径`
            url += '?' + paramsStr;
            // 2.4 发送get请求
            promise = Axios.get(url)
        }else if('DELETE' === type.toUpperCase()){
            // 2.1 拼接请求字符串
            let paramsStr = '';
            Object.keys(params).forEach(key =>{
                paramsStr += key + '=' + params[key] + '&'
            });
            // 2.2 过滤最后的&
            if(paramsStr !== ''){
                paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'))
            }
            // 2.3 完整路径
            url += '?' + paramsStr;
            // Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
            promise = Axios.delete(url); //
        }else if('POST' === type.toUpperCase()){
            if ('form' === contentType.toLowerCase()) {
                promise = Axios.post(url, Qs.stringify(params), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            } else if ('json' === contentType.toLowerCase()) {
                promise = Axios.post(url, JSON.stringify(params), {headers: {'Content-Type': 'application/json;charset=utf-8'}})
            } else if ('file' === contentType.toLowerCase()) {
                promise = Axios.post(url, params, {headers: {'Content-Type': 'application/form-data'}})
            } else {
                promise = Axios.post(url, params)
            }
        }
        // 3. 返回请求的结果
        promise.then((response)=>{
            resovle(response);
        }).catch(error => {
            reject(error)
        })
    })
}